// src/hooks/useScreenSize.ts
import { ref, onMounted, onUnmounted } from 'vue'

type DebounceOptions = {
  wait?: number
  leading?: boolean
}

export default function useScreenSize(options?: DebounceOptions) {
  const width = ref(0)
  const height = ref(0)
  
  // 处理防抖函数
  const debounce = (fn: Function, wait: number, leading = false) => {
    let timeout: NodeJS.Timeout | null = null
    return (...args: any[]) => {
      const later = () => {
        timeout = null
        if (!leading) fn(...args)
      }
      const callNow = leading && !timeout
      if (timeout) clearTimeout(timeout)
      timeout = setTimeout(later, wait)
      if (callNow) fn(...args)
    }
  }

  // 更新尺寸函数
  const updateSize = () => {
    if (typeof window !== 'undefined') {
      width.value = window.innerWidth
      height.value = window.innerHeight
    }
  }

  // 带防抖的更新函数
  const debouncedUpdate = options?.wait 
    ? debounce(updateSize, options.wait, options.leading)
    : updateSize

  // 初始化尺寸
  updateSize()

  // 生命周期处理
  onMounted(() => {
    window.addEventListener('resize', debouncedUpdate)
    // 兼容移动端旋转屏幕
    window.addEventListener('orientationchange', debouncedUpdate)
  })

  onUnmounted(() => {
    window.removeEventListener('resize', debouncedUpdate)
    window.removeEventListener('orientationchange', debouncedUpdate)
  })

  return {
    width,
    height,
    isMobile: () => width.value < 768,    // 常用移动端断点
    isTablet: () => width.value >= 768 && width.value < 1024,
    isDesktop: () => width.value >= 1024
  }
}